package cn.joyconn.tools.mysqlbackup.task.utils.rsyncDir;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.logging.log4j.util.Strings;

import cn.joyconn.tools.mysqlbackup.task.utils.LogHelper;
import cn.joyconn.tools.mysqlbackup.task.utils.ProcessUtil;

public class RsyncDirTool {
    public static void backup(String hostIP,String port, String userName, String passwordFile, String remotePath, String localSaveBaseDir        
        ) {
        File saveFile = new File(localSaveBaseDir);
        if (!saveFile.exists()) {// 如果目录不存在
            return;
        }
        // if (!savePath.endsWith(File.separator)) {
        //     savePath = savePath + File.separator;
        // }
        StringBuilder stringBuilder = new StringBuilder();
        // stringBuilder.append("mariabackup  ").append(" --host").append(hostIP).append(" --port=").append(port)
        //             .append(" --no-timestamp --socket=/var/lib/mysql/mysql.sock");
        //rsync -av /data/test/ JoyconnRsync@sdfy.joyconn.cn::data  --password-file=/data/backup-app/resources/rsync.password  --port=10013 --delete-after
        if(isWindows()){
            if(localSaveBaseDir.length()>2&&localSaveBaseDir.charAt(1)==':'){
                localSaveBaseDir="/cygdrive/"+localSaveBaseDir.substring(0, 1)+"/"+localSaveBaseDir.substring(2);
            }
            while(localSaveBaseDir.indexOf("\\")>-1){
                localSaveBaseDir=localSaveBaseDir.replace("\\", "/");
            }
            if(passwordFile.length()>2&&passwordFile.charAt(1)==':'){
                passwordFile="/cygdrive/"+passwordFile.substring(0, 1)+"/"+passwordFile.substring(2);
            }
            while(passwordFile.indexOf("\\")>-1){
                passwordFile=passwordFile.replace("\\", "/");
            }
            
        }
        stringBuilder.append("rsync -av ").append(localSaveBaseDir).append(" ")
            .append(userName).append("@").append(hostIP).append("::").append(remotePath)
            .append(" --password-file=").append(passwordFile)
            .append(" --port=").append(port)
            .append(" --delete-after");
      
    
        try {
            LogHelper.logger().info("开始执行:"+stringBuilder.toString());    
            Process process = ProcessUtil.doProcess(stringBuilder.toString());
            // int processResult = process.waitFor();
            // if (processResult == 0) {// 0 表示线程正常终止。
            //     LogHelper.logger().info("数据库备份文件同步成功");
            // }
        } catch (IOException e) {
            LogHelper.logger().info("数据库备份文件同步异常");
            e.printStackTrace();
        } 
        // catch (InterruptedException e) {
        //     LogHelper.logger().info("数据库备份文件同步异常");
        //     e.printStackTrace();
        // }
    }
    public static boolean isWindows() {
		return System.getProperties().getProperty("os.name").toUpperCase().indexOf("WINDOWS") != -1;
	}

}
